<?php

class producerController extends baseController {
	private $m_producerApiView;	
	private $m_producerPositionView;
	
	public function position (){
		
		//require_once ('Models/Xml2Json.php');
		
		$array2Xml = new Array2Xml("positions");
		$producerModel = new ProducerModel();
		$validator = new Validate();

		//Sparar undan requestet i ett objekt. 
		$requestObject = RestUtils::processRequest();
		$requestVariables = $requestObject->getRequestVars();
		//Hämtar ev. parametrar 
		$parameters = $this->m_command->GetParameters();
		//Tar bort det första elementet som är funktionsnamnet. 
		array_shift($parameters);
		$validator->ValidateParameters($parameters);

		switch($requestObject->getMethod())
		{
			case 'get':	
		
				$position = ($producerModel->GetPositions($requestVariables, $parameters));
				if($position == null){
					RestUtils::sendResponse("404", "<error>Kunde inte hitta positionen</error>", "text/xml");
				}elseif($position == false){
					RestUtils::sendResponse("500", "<error>Serverfel</error>", "text/xml");
				}				
				//$xml = $array2Xml->GetXml($position);
				$result = $array2Xml->buildXMLData($position, "positions", $xml_version = '1.0', $xml_encoding = 'UTF-8');				
				//header("content-type: text/xml");
				//echo $result;				
				RestUtils::sendResponse("200", $result, "text/xml");
				break;
			case 'delete':	
		
				$result = $producerModel->DeletePosition($parameters[0]);
				if($result == false){
					
					RestUtils::sendResponse("500", "<error>Serverfel</error>", "text/xml");
				}else{
					RestUtils::sendResponse("200", "<success>Positionen med id: ".$parameters[0]." har tagits bort</success>", "text/xml");	
				}
				
			case 'put':
				if(count($parameters) != 1){
					RestUtils::sendResponse("400", "<error>Du har angivit fel url</error>", "text/xml");
				}
				$result = $producerModel->UpdatePosition($requestVariables, $parameters[0]);

				if($result == true){
					RestUtils::sendResponse("200", "<success>Positionen med id: ".$parameters[0]." har uppdaterats</success>", "text/xml");
					
				}elseif($result ==null){
					RestUtils::sendResponse("404", "<error>Kunde inte hitta positionen</error>", "text/xml");
				}else{
					RestUtils::sendResponse("500", "<error>Serverfel</error>", "text/xml");	
				}
						
				break;
			case 'post':
				if(count($parameters) != 0){
					RestUtils::sendResponse("400", "<error>Du har angivit fel url</error>", "text/xml");
				}
				$result = $producerModel->CreatePosition($requestVariables);
				if($result == true){
					RestUtils::sendResponse("201", "<success>Positionen har lagts till</success>", "text/xml");
					
				}else{
					RestUtils::sendResponse("500", "<error>Serverfel</error>", "text/xml");
				}
		}
	}
}

